package com.qishenyuan.competition.config;

import org.apache.catalina.connector.Connector;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

@Configuration
@ConditionalOnProperty(prefix = "custom", name = "enable", havingValue = "true")
@Slf4j
public class HttpConfiguration {

    @Value("${custom.http-port}")
    private Integer httpPort;

    @Bean
    WebServerFactoryCustomizer<TomcatServletWebServerFactory> enableTomcatHttpConnector() {
        return tomcatServletWebServerFactory -> {
            Connector httpConnector = new Connector(TomcatServletWebServerFactory.DEFAULT_PROTOCOL);
            httpConnector.setScheme("http");
            httpConnector.setPort(httpPort);
            log.info("enableTomcatHttpConnector | tomcatHttpPort = {}", httpPort);
            List<Connector> connList = tomcatServletWebServerFactory.getAdditionalTomcatConnectors();
            log.info("enableTomcatHttpConnector | before | connList.size = {}", connList.size());
            tomcatServletWebServerFactory.addAdditionalTomcatConnectors(httpConnector);
            connList = tomcatServletWebServerFactory.getAdditionalTomcatConnectors();
            log.info("enableTomcatHttpConnector | after | connList.size = {}", connList.size());
        };
    }


}
